package Util::Tuan::TuansUtil;
use Moose;
use namespace::autoclean;
use JSON;
use Time::Piece;
use Time::Seconds;

has 'schema' => (
	is => 'rw',
	required => 1,
	isa => 'DBIx::Class::Schema',
);

sub check_params {
	my ($self, $c, $rec_user_name, $rec_user_address, $rec_user_phone, $tuan_university, $need_register, $email_address, $amounts, $storeIds) = @_;	
	my @message;
        my %storeAmount;
        my $sign = 0;
        my $flag = 0;
        my $index = 0;
        if ($rec_user_name eq '') {
                my $text = "您没有输入订货人姓名";
                push(@message, $text);
        }

        if ($rec_user_address eq '') {
                my $text = "您没有输入收货人地址";
                push(@message, $text);
        }

        if ($rec_user_phone eq '') {
                my $text = "您没有输联系电话";
                push(@message, $text);
        }

        if ($tuan_university eq '') {
                my $text = "您参拼时没有选择具体高校";
                push(@message, $text);
        }
        if($need_register eq '1') {
                if ($email_address eq '') {
                        my $text = "您匿名参拼时没有填写email地址";
                        push(@message, $text);
                }
                if (!Email::Valid->address("$email_address")){
                        my $text = "email地址无效";
                        push(@message, $text);
                }
                my @exist_users = $c->model('Users::UsersSearchModel')->get_user_by_email($email_address);
                if(scalar(@exist_users) > 0) {
                        my $text = "您已经使用该email地址注册过，请正确登录后再下单";
                        push(@message, $text);
                }
        }

	        if($rec_user_phone =~ /^1[0-9]{10}$/) {
        }
        else {
                my $text = "您输入的联系手机号码有误";
                push(@message, $text);
        }

        foreach (@$amounts) {
                if($_ != 0) {
                        if(m/^[1-9]\d*/) {
                                if($_ >= 10000) {
                                        $sign = 1;
                                        my $text = "你输入的购买件数过大";
                                        push(@message, $text);
                                } else {
                                        $sign = 1;
                                        my $storeId = $storeIds->[$index];
                                        $storeAmount{$storeId} = $_;
                                }
                        } else {
                                $flag = 1;
                        }
                }
                $index ++;
        }
        if($sign == 0) {
                my $text = "你没有选择购买任何商品";
                push(@message, $text);

        }
        if($flag == 1) {
                my $text = "你输入的购买件数不是合法的数字";
                push(@message, $text);
        }
	return (\@message, \%storeAmount)

}

sub send_email_to_anonymous_user{
	my ($self, $c, $password, $tuan, $user_tuan, $need_register, $rec_user_phone, $sender) = @_;
	my (%params, %options);
	$options{INCLUDE_PATH} = $c->config->{email_template_path};
	$params{username} = $c->user->username;
	$params{email}  = $c->user->email_address;
	$params{password}  = $password;
	$params{tuan_name}  = $tuan->name;
	$params{tuan_id}  = $tuan->id;
	if($need_register eq '1') {
		my $md5 = Digest::MD5->new;
		$md5->add($c->user->email_address . '||' . $user_tuan->id);
		my $verify_url = $c->config->{verification_user_tuan_url} . "?utid=" . $user_tuan->id . "&code=" . $md5->hexdigest;
		$params{notice}  = "由于您使用了匿名参拼功能，系统已快速为您注册了拼单族用户，默认用户名为:".$c->user->username."，默认密码为您参团时输入的手机号码:".$rec_user_phone."，您可以随时在个人主页修改上述信息。您的匿名订单尚未在拼单族确认，营长将不会通知发货，请点击以下链接完成订单确认功能。";
		$params{verification_url}  = $verify_url;
	}

	my $yuji_tihuo_time = $tuan->yuji_tihuo_time;
	if($yuji_tihuo_time =~ /\|/) {
		$params{is_dingqi}  = "Y";
		my @dingqi_tihuo_times =split(/|/,$yuji_tihuo_time);
		my $t = localtime;
		my $current_day_of_week = $t->day_of_week;
		my $next_weekday;
		my $current_next_weekday = 8;
		my $min_weekday = 7;
		my $is_next_week = 0;
		my $day_count = 0;
		foreach(@dingqi_tihuo_times) {
			if($day_count % 2 == 1) {
				if($_ > $current_day_of_week) {
					$next_weekday = $_;
					if($next_weekday < $current_next_weekday) {
						$current_next_weekday = $next_weekday;
					}
				}
				if($_ < $min_weekday) {
					$min_weekday = $_;
				}
			}
			$day_count = $day_count + 1;
		}
		my $time_diff;
		if($current_next_weekday < 7) {
			$time_diff = $current_next_weekday - $current_day_of_week;
		}
		else {
			$time_diff = $min_weekday + 7 - $current_day_of_week;
		}
		my $yuji_time = localtime;
		while($time_diff > 0) {
			$yuji_time += ONE_DAY;
			$time_diff = $time_diff - 1;
		}
		$yuji_tihuo_time = $yuji_time->ymd;
	}
	$params{yuji_tihuo_time}  = $yuji_tihuo_time;
	my $title = "参拼成功";
	my $template = "email/join_tuan_success.html.tt";
	$sender->send($c->user->email_address, $title, $template, \%params, \%options);
	return \%params;
}

sub send_email_to_yingzhang{
	my ($self, $need_register, $c, $create_user, $tuan, $rec_user_name, $rec_user_phone, $rec_user_address, $join_tuan_comment, $yuji_tihuo_time, $sender, $storeNameAmount) = @_;
	my (%params1, %options1);
	$options1{INCLUDE_PATH} = $c->config->{email_template_path};
	$params1{username} = $create_user->username;
	$params1{email}  = $create_user->email_address;
	$params1{tuan_name}  = $tuan->name;
	$params1{tuan_id}  = $tuan->id;
	$params1{client_name}  = $rec_user_name;
	$params1{client_cellphone}  = $rec_user_phone;
	$params1{client_address}  = $rec_user_address;
	$params1{client_note}  = $join_tuan_comment;
	$params1{storeAmount}  = $storeNameAmount;
	$params1{tuan_id}  = $tuan->id;
	if($need_register eq '1') {
		$params1{notice}  = "请注意该用户为匿名下单，建议在发货之前联系用户确认订货数量。";
	}

	my $title = "【".$tuan->name."】订单通知";
	$params1{yuji_tihuo_time}  = $yuji_tihuo_time;
	my $template = "email/join_tuan_success_yingzhang.html.tt";
	$sender->send($create_user->email_address, $title, $template, \%params1, \%options1);

}

sub update_contact_info{
	my($self, $c, $need_register, $email_address, $rec_user_phone, $rec_user_name, $rec_user_address, $create_new_contact, $orig_contact_id, $user_id, $tuan_university, $new_contact_id) = @_;
	my $user;
	if ($need_register eq '1') {
		my @nicknames = split(/@/,$email_address);
		my $nickname = $nicknames[0];
		if(length($nickname) > 8) {
			$nickname = substr($nickname,0,8);
		}
		my $exist_user_check = $c->model('Users::UsersSearchModel')->username_check($nickname);
		my $newnickname = $nickname;
		my $rand = new String::Random;
		unless($exist_user_check eq 'true') {
			$newnickname = $nickname . $rand->randpattern('nnnn');
			$exist_user_check = $c->model('Users::UsersSearchModel')->username_check($newnickname);
		}
		my $commented_item = $c->model('CommentedItem::CommentedItemModel')->create('1');
		$user = $c->model('Users::UserRegisterModel')->register('', $newnickname, $rec_user_phone, $nickname, $commented_item->id, $email_address, $c->config->{image_path}, '', '', $tuan_university, '', '');
		$user->update({active => 'Y'});
		$user_id = $user->id;
	}
	if($create_new_contact eq '1')
	{
		my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->create($user_id,'Y','2999-01-01',$rec_user_name,$rec_user_address,$rec_user_phone);
		if($orig_contact_id)
		{
			my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_status($orig_contact_id,'N');
		}
	}
	else {
		if($orig_contact_id)
		{
			if($orig_contact_id ne $new_contact_id)
			{
				my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_status($orig_contact_id,'N');
				$contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_status($new_contact_id,'Y');
				$contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_contact($new_contact_id, $rec_user_name,$rec_user_address,$rec_user_phone);
			}
			else
			{
				my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->find($orig_contact_id);
				#my $t = Time::Piece->strptime("29990101", "%Y%m%d");
				if($contact->effective_to->year() == 2999)
				{
					$contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_contact($orig_contact_id, $rec_user_name,$rec_user_address,$rec_user_phone);
				}
				else
				{
					$contact = $c->model('UserDeliverContact::UserDeliverContactModel')->create($user_id,'Y','2999-01-01',$rec_user_name,$rec_user_address,$rec_user_phone);
				}
			}
		}
		else
		{
			my $contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_status($new_contact_id,'Y');
			$contact = $c->model('UserDeliverContact::UserDeliverContactModel')->update_contact($new_contact_id, $rec_user_name,$rec_user_address,$rec_user_phone);
		}
	}
	return $user;
}


__PACKAGE__->meta->make_immutable;

1;
